import React, { useState } from 'react';
import { 
  Form, 
  Input, 
  Button, 
  Card, 
  message, 
  Space,
  Typography,
  Divider
} from 'antd';
import { 
  ArrowLeftOutlined, 
  UserOutlined, 
  LockOutlined, 
  MailOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import styled from '@emotion/styled';

const { Title, Text } = Typography;

interface RegisterFormValues {
  username: string;
  email: string;
  password: string;
  confirmPassword: string;
}

// Styled Components
const RegisterContainer = styled.div`
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
`;

const BackButton = styled(Button)`
  position: absolute;
  top: 20px;
  left: 20px;
  color: #fff;
  border: 1px solid rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  
  &:hover {
    background: rgba(255, 255, 255, 0.2);
    border-color: rgba(255, 255, 255, 0.5);
    color: #fff;
  }
`;

const RegisterContent = styled.div`
  width: 100%;
  max-width: 400px;
`;

const StyledCard = styled(Card)`
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
  
  .ant-card-body {
    padding: 40px 32px;
  }
`;

const RegisterHeader = styled.div`
  text-align: center;
  margin-bottom: 32px;
  
  h2 {
    margin-bottom: 8px;
    color: #1f2937;
    font-weight: 600;
  }
`;

const RegisterButton = styled(Button)`
  height: 48px;
  border-radius: 8px;
  font-weight: 500;
  font-size: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
    background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  }
`;

const LoginLink = styled(Button)`
  padding: 0;
  font-weight: 500;
`;

const RegisterFooter = styled.div`
  text-align: center;
  
  .ant-space {
    justify-content: center;
  }
`;

const StyledInput = styled(Input)`
  border-radius: 6px;
  border: 1px solid #d1d5db;
  transition: all 0.3s;
  
  &:hover,
  &:focus,
  &.ant-input-affix-wrapper-focused {
    border-color: #667eea;
    box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
  }
`;

const StyledPasswordInput = styled(Input.Password)`
  border-radius: 6px;
  border: 1px solid #d1d5db;
  transition: all 0.3s;
  
  &:hover,
  &:focus,
  &.ant-input-affix-wrapper-focused {
    border-color: #667eea;
    box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
  }
`;

const StyledFormItem = styled(Form.Item)`
  .ant-form-item-label {
    font-weight: 500;
    
    > label {
      color: #374151;
    }
  }
`;

const StyledDivider = styled(Divider)`
  color: #9ca3af;
  
  &::before,
  &::after {
    border-top: 1px solid #e5e7eb;
  }
`;

// 响应式样式 - 修复Emotion组件选择器问题
const MobileWrapper = styled.div`
  @media (max-width: 480px) {
    /* 移除组件选择器，使用类名选择器替代 */
    .register-container {
      padding: 16px;
    }
    
    .back-button {
      top: 16px;
      left: 16px;
    }
    
    .styled-card .ant-card-body {
      padding: 24px 20px;
    }
  }
`;

const SignUp: React.FC = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  const handleBack = () => {
    navigate(-1); // 返回上一页
  };

  const onFinish = async (values: RegisterFormValues) => {
    setLoading(true);
    try {
      // 模拟注册API调用
      await mockRegisterApi(values);
      message.success('注册成功！');
      // 注册成功后跳转到登录页或其他页面
      navigate('/login');
    } catch (error) {
      message.error('注册失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const mockRegisterApi = (values: RegisterFormValues): Promise<void> => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // 模拟随机失败
        if (Math.random() > 0.3) {
          resolve();
        } else {
          reject(new Error('注册失败'));
        }
      }, 1500);
    });
  };

  return (
    <MobileWrapper>
      <RegisterContainer className="register-container">
        <BackButton 
          type="text" 
          icon={<ArrowLeftOutlined />} 
          onClick={handleBack}
          className="back-button"
        >
          返回
        </BackButton>
        
        <RegisterContent>
          <StyledCard className="styled-card">
            <RegisterHeader>
              <Title level={2}>创建账号</Title>
              <Text type="secondary">开始您的旅程</Text>
            </RegisterHeader>

            <Form
              form={form}
              name="register"
              onFinish={onFinish}
              layout="vertical"
              size="large"
              scrollToFirstError
            >
              <StyledFormItem
                name="username"
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名!' },
                  { min: 3, message: '用户名至少3个字符!' },
                  { max: 20, message: '用户名最多20个字符!' },
                  { pattern: /^[a-zA-Z0-9_]+$/, message: '只能包含字母、数字和下划线!' }
                ]}
              >
                <StyledInput 
                  prefix={<UserOutlined />} 
                  placeholder="请输入用户名" 
                />
              </StyledFormItem>

              <StyledFormItem
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱!' },
                  { type: 'email', message: '请输入有效的邮箱地址!' }
                ]}
              >
                <StyledInput 
                  prefix={<MailOutlined />} 
                  placeholder="请输入邮箱" 
                />
              </StyledFormItem>

              <StyledFormItem
                name="password"
                label="密码"
                rules={[
                  { required: true, message: '请输入密码!' },
                  { min: 6, message: '密码至少6个字符!' },
                  { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, message: '必须包含大小写字母和数字!' }
                ]}
              >
                <StyledPasswordInput
                  prefix={<LockOutlined />}
                  placeholder="请输入密码"
                  iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                />
              </StyledFormItem>

              <StyledFormItem
                name="confirmPassword"
                label="确认密码"
                dependencies={['password']}
                rules={[
                  { required: true, message: '请确认密码!' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不一致!'));
                    },
                  }),
                ]}
              >
                <StyledPasswordInput
                  prefix={<LockOutlined />}
                  placeholder="请再次输入密码"
                  iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                />
              </StyledFormItem>

              <Form.Item>
                <RegisterButton 
                  type="primary" 
                  htmlType="submit" 
                  loading={loading}
                  block
                >
                  注册
                </RegisterButton>
              </Form.Item>
            </Form>

            <StyledDivider plain>或者</StyledDivider>

            <RegisterFooter>
              <Space>
                <Text>已有账号?</Text>
                <LoginLink 
                  type="link" 
                  onClick={() => navigate('/login')}
                >
                  立即登录
                </LoginLink>
              </Space>
            </RegisterFooter>
          </StyledCard>
        </RegisterContent>
      </RegisterContainer>
    </MobileWrapper>
  );
};

export default SignUp;